import { createStore } from 'vuex'

export default createStore({
  state: {
    shop:{
      hoverGame: 5,
    },
    curGame: -1,
    // 游戏数据
    allGame: [],
    gameLoad: false,
    cartGood: null,
    // 用户数据
    mid: -1,
    userInfo: JSON.parse(localStorage.getItem('userdata') || '{}'),
    userFriends: null,
    infoLoad: false,
    // 信息编辑弹窗
    infoEdit: false,
    curView: 2,
    // 视频播放控制
    videoPlay: false,
    // 天气信息
    weather: {},
    // 身份, 0是普通用户，1是开发者，2是管理员
    identity: 0,
    // 服务器地址
    baseUrl: 'http://159.75.133.177:8888',
  },
  getters: {
  },
  mutations: {
    saveCurGame(state,num){
      state.curGame = num;
    },
    changeHover(state,num){
      state.shop.hoverGame = num;
    },
    changeView(state,num){ 
      // console.log('改变'+num);
      state.curView = num;
    },
    saveGames(state, payload){
      let { gameList, flag } = payload; // 从 payload 中解构出 gameList 和 flag
      console.log(flag);
      if(flag!=''){
        // 取出 state.allGame 的前 5 个元素
        const top5Games = state.allGame.slice(0, 5);
        // 拼接传入的 gameList
        gameList = [...top5Games, ...gameList];
        state.shop.hoverGame = 5
      }
      gameList.forEach((item,index)=>{
        // 处理图片和视频字段
        const mediaFields = ['photo', 'photoa', 'photob', 'photoc', 'photod', 'icon', 'video', 'path'];
        mediaFields.forEach(field => {
          if (item[field] && !item[field].startsWith('http')) {
            item[field] = `${state.baseUrl}/${item[field]}`;
          }
        });
      })
      console.log('filter',gameList)
      state.allGame = gameList;
      state.gameLoad = true;
    },
    // 保存用户信息
    saveUserInfo(state,info){
      localStorage.setItem('userdata', JSON.stringify(info));
      if(!info.photo.startsWith('http')){
        info.photo = `${state.baseUrl}/${info.photo}`
      }
      console.log(info)
      state.identity = info.level;
      state.userInfo = info;
      state.infoLoad = true;
    },
    updateInfo(state,query){
      for (let key in query) {
        state.userInfo[key]=query[key];
      }
    },
    saveMid(state,mid){
      state.mid = mid;
    },
    switchInfoEdit(state,tag){
      state.infoEdit = tag;
    },
    changeVideoPlay(state,tag){
      state.videoPlay = tag;
    },
    saveWeather(state,data){
      state.weather = data;
    }
  },
  actions: {
  },
  modules: {
  }
})
